import xml.etree.ElementTree as ET

class MessageParser:
    """企业微信消息解析器"""
    
    def __init__(self):
        """初始化消息解析器"""
        pass

    def parse_xml_message(self, xml_content):
        """
        解析XML格式的企业微信消息
        
        Args:
            xml_content: XML格式的消息内容
            
        Returns:
            dict: 解析后的消息字典，包含消息类型、发送者、接收者、内容等信息
        """
        try:
            root = ET.fromstring(xml_content)
            
            # 提取基本信息，添加空值处理
            def get_text_safe(node, tag):
                """安全获取文本内容，处理空值"""
                n = node.find(tag)
                return n.text if n is not None else ""
            
            msg_type = get_text_safe(root, 'MsgType')
            from_user = get_text_safe(root, 'FromUserName')
            to_user = get_text_safe(root, 'ToUserName')
            create_time = get_text_safe(root, 'CreateTime')
            msg_id = get_text_safe(root, 'MsgId')
            
            # 根据消息类型提取内容
            content = self._extract_content_by_type(root, msg_type)
            
            return {
                'msg_type': msg_type,
                'from_user': from_user,
                'to_user': to_user,
                'create_time': create_time,
                'msg_id': msg_id,
                'content': content,
                'raw_xml': xml_content
            }
        except Exception as e:
            print(f"解析XML消息失败: {str(e)}")
            return None

    def _extract_content_by_type(self, root, msg_type):
        """
        根据消息类型提取内容
        
        Args:
            root: XML根节点
            msg_type: 消息类型
            
        Returns:
            str: 提取的内容
        """
        def get_text_safe(node, tag):
            """安全获取文本内容，处理空值"""
            n = node.find(tag)
            return n.text if n is not None else ""
        
        content = ""
        
        if msg_type == 'text':
            # 企业微信客服消息格式：<Text><Content>
            text_node = root.find('Text')
            if text_node is not None and text_node.find('Content') is not None:
                content = text_node.find('Content').text or ""
            else:
                # 兼容自建应用格式：<Content>
                content_node = root.find('Content')
                if content_node is not None:
                    content = content_node.text or ""
        elif msg_type == 'image':
            image_node = root.find('Image')
            if image_node is not None and image_node.find('MediaId') is not None:
                media_id = image_node.find('MediaId').text or ""
                content = f"[图片消息] {media_id}"
            else:
                pic_url = get_text_safe(root, 'PicUrl')
                media_id = get_text_safe(root, 'MediaId')
                content = f"[图片消息] {pic_url or media_id}"
        elif msg_type == 'voice':
            voice_node = root.find('Voice')
            if voice_node is not None and voice_node.find('MediaId') is not None:
                media_id = voice_node.find('MediaId').text or ""
                content = f"[语音消息] {media_id}"
            else:
                media_id = get_text_safe(root, 'MediaId')
                format_type = get_text_safe(root, 'Format')
                content = f"[语音消息] 格式: {format_type}"
        elif msg_type == 'video':
            video_node = root.find('Video')
            if video_node is not None and video_node.find('MediaId') is not None:
                media_id = video_node.find('MediaId').text or ""
                content = f"[视频消息] {media_id}"
            else:
                media_id = get_text_safe(root, 'MediaId')
                thumb_media_id = get_text_safe(root, 'ThumbMediaId')
                content = f"[视频消息]"
        elif msg_type == 'location':
            location_node = root.find('Location')
            if location_node is not None:
                label = get_text_safe(location_node, 'Label')
                x = get_text_safe(location_node, 'Location_X')
                y = get_text_safe(location_node, 'Location_Y')
                content = f"[位置消息] {label} ({x}, {y})"
            else:
                label = get_text_safe(root, 'Label')
                x = get_text_safe(root, 'Location_X')
                y = get_text_safe(root, 'Location_Y')
                content = f"[位置消息] {label} ({x}, {y})"
        elif msg_type == 'link':
            title = get_text_safe(root, 'Title')
            description = get_text_safe(root, 'Description')
            url = get_text_safe(root, 'Url')
            content = f"[链接消息] {title}: {description}"
        elif msg_type == 'event':
            event = get_text_safe(root, 'Event')
            content = f"[事件消息] {event}"
        else:
            content = f"[{msg_type}类型消息]"
        
        return content

    def create_reply_xml(self, to_user, from_user, create_time, msg_type, content):
        """
        创建回复消息的XML
        
        Args:
            to_user: 接收者
            from_user: 发送者
            create_time: 创建时间
            msg_type: 消息类型
            content: 消息内容
            
        Returns:
            str: XML格式的回复消息
        """
        xml_template = f"""<xml>
<ToUserName><![CDATA[{to_user}]]></ToUserName>
<FromUserName><![CDATA[{from_user}]]></FromUserName>
<CreateTime>{create_time}</CreateTime>
<MsgType><![CDATA[{msg_type}]]></MsgType>
<Content><![CDATA[{content}]]></Content>
</xml>"""
        return xml_template

    def is_text_message(self, msg_type):
        """判断是否为文本消息"""
        return msg_type == 'text'

    def is_media_message(self, msg_type):
        """判断是否为媒体消息（图片、语音、视频）"""
        return msg_type in ['image', 'voice', 'video']

    def is_location_message(self, msg_type):
        """判断是否为位置消息"""
        return msg_type == 'location'

    def is_event_message(self, msg_type):
        """判断是否为事件消息"""
        return msg_type == 'event' 